﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Text;
using MyLib;
namespace WebPortal
{
    public partial class Assign : System.Web.UI.Page
    {
        private StringBuilder StrSQL;
        protected void Page_Load(object sender, EventArgs e)
        {
            Button1.Text = Workflow.Resources.lang.Assign_AssignButton;
            if (Request.QueryString["TaskID"] != null)
            {
                TaskIDs.Value = Request.QueryString["TaskID"].ToString().Trim();
            }
            if (!IsPostBack)
            {
                BingProcess();
            }
        }

        private void BingProcess()
        {
            StrSQL = new StringBuilder();
            StrSQL.AppendLine("select PROCESSNAME from INITIATE");
            dropProcessName.DataSource = DataAccess.Instance("UltDB").ExecuteDataTable(StrSQL.ToString());
            dropProcessName.DataTextField = "PROCESSNAME";
            dropProcessName.DataValueField = "PROCESSNAME";
            dropProcessName.DataBind();
            dropProcessName.Items.Insert(0, new ListItem("", ""));
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            Ultimus.WFServer.Task pTask = new Ultimus.WFServer.Task();

            //OrgChart.Entity.UserEntity CurrentUser = new OrgChart.Entity.UserEntity();
            //if (HttpContext.Current.Session["CurrentUser"] != null)
            //{
            //    CurrentUser = HttpContext.Current.Session["CurrentUser"] as OrgChart.Entity.UserEntity;
            //}
            string pFromUser = Page.User.Identity.Name.Replace("\\", "/");
            string pToUser = AssignUserAccount.Value;
            string pEndDate = txtFutureTaskDate.Text.Trim() == "" ? DateTime.Now.ToString() : txtFutureTaskDate.Text;

            int pMode = 0;
            if (this.RadioButton1.Checked)
            {
                pMode = 1;//仅限选定的任务
            }
            else if (this.RadioButton2.Checked)
            {
                pMode = 2;//所有现有的任务
            }
            else if (this.RadioButton3.Checked)
            {
                pMode = 3;//所有将来的任务  
                pEndDate = this.txtFutureTaskDate.Text;
            }
            else if (this.RadioButton4.Checked)
            {
                pMode = 4;//按流程指派
            }
            bool result = false;
            if (pMode == 1)
            {
                string[] TaskIDArray = TaskIDs.Value.Split(',');
                foreach (string pTaskID in TaskIDArray)
                {
                    if (pTaskID.Trim() == "")
                        continue;
                    result = this.SetAssign(pTaskID, pFromUser, pToUser, pMode, DateTime.Parse(pEndDate));
                }
            }
            else if (pMode == 4)
            {
                string strProcessName = dropProcessName.SelectedItem.Text;
                string dBegin = this.txtBegin.Text;
                string dEnd = this.txtEnd.Text;
                if (this.isExistAssign(strProcessName, pFromUser, dBegin))
                {
                    MessageBox("alert('" + Workflow.Resources.lang.Assign_Msg1 + "')");
                    return;
                }
                result = this.SetProcAssign(strProcessName, pFromUser, pToUser, dBegin, dEnd);
            }
            else
            {
                //将来指派和所有任务指派不需要循环
                result = this.SetAssign("", pFromUser, pToUser, pMode, DateTime.Parse(pEndDate));
            }
            if (result)
            {
                MessageBox("alert('" + Workflow.Resources.lang.Assign_Msg2 + "');window.close();");
            }
            else
            {
                MessageBox("alert('" + Workflow.Resources.lang.Assign_Msg3 + "')");

            }
        }

        private void MessageBox(string script)
        {
            this.Page.ClientScript.RegisterClientScriptBlock(this.Page.GetType(), "javascript", "<script language='javascript' defer>" + script + "</script>");
        }

        /// <summary>
        /// 是否存在该流程的指派
        /// </summary>
        /// <param name="strProcessName"></param>
        /// <param name="pFromUser"></param>
        /// <param name="dBegin"></param>
        /// <returns></returns>
        private bool isExistAssign(string strProcessName, string pFromUser, string dBegin)
        {
            // throw new NotImplementedException();
            string strSql = " select COUNT(id) from SYS_ASSIGNMENT " +
                                " where IsEnable = 1 " +
                                " and ProcessName='" + strProcessName + "' " +
                                " and TskUser ='" + pFromUser + "'" +
                                " and EdDate>to_date('" + dBegin + "','yyyy-mm-dd') ";
            DataTable dt = DataAccess.Instance("BizDB").ExecuteDataTable(strSql);
            if (Convert.ToInt32(dt.Rows[0][0]) > 0)
                return true;
            return false;
        }

        private bool SetProcAssign(string strProcessName, string pFromUser, string pToUser, string dBegin, string dEnd)
        {
            //throw new NotImplementedException();
            string strSql = "INSERT INTO SYS_ASSIGNMENT " +
                                                   "(ID " +
                                                   ",ProcessName " +
                                                  " ,TskUser " +
                                                  " ,TskAssignUser" +
                                                  " ,BgDate" +
                                                  " ,EdDate" +
                                                  " ,AssignCount" +
                                                  " ,IsEnable)" +
                                                  " VALUES ('" +
                                                  Guid.NewGuid().ToString() +
                                                  "' ,'" + strProcessName.Trim() +
                                                  "' ,'" + pFromUser +
                                                  "' , '" + pToUser +
                                                  "' ,to_date('" + dBegin +
                                                  "','yyyy-MM-dd') ,to_date('" + dEnd +
                                                   "','yyyy-MM-dd'),0,1)";
            int count = DataAccess.Instance("BizDB").ExecuteNonQuery(strSql);
            if (count > 0)
                return true;
            else
                return false;
        }

        private bool SetAssign(string pTaskID, string pFromUser, string pToUser, int pMode, DateTime pDate)
        {
            bool result = false;
            try
            {
                Ultimus.OC.User pUserTask = null;
                Ultimus.OC.OrgChart porg = new Ultimus.OC.OrgChart(); 
                result = porg.FindUser(pFromUser, "", 0, out pUserTask);
                switch (pMode)
                {
                    case 1:
                        Ultimus.WFServer.Task pTask = new Ultimus.WFServer.Task();
                        pTask.InitializeFromTaskId(pTaskID);
                        result = pTask.AssignTask(pToUser);
                        break;
                    case 2:
                        pUserTask.AssignAllCurrentTasks(pToUser);
                        break;
                    case 3:
                        pUserTask.AssignAllFutureTasks(pToUser, pDate.ToOADate());
                        break;
                }
                return result;

            }
            catch (Exception ex)
            {
                return false;
            }
        }
    }
}